import { dialogForm, DialogFormOptions } from "@/utils/dialogForm";
import { insertMarketDatabase, getDict } from "@/api/modules/sys";
import { useDict } from "@/hooks/useDict";
import { ref } from "vue";
export const useAdd = () => {
  const config = ref({});
  const { dict } = useDict();
  let defaultOptions = ref<any>({});
  let typeList = ref<any>([]);

  // 加载字典数据
  const loadNode = async (node: any, resolve: (data: any) => void) => {
    if (node.value) {
      const { data } = await getDict({ parentId: node.value });
      data.forEach((item: any) => {
        item.hasChild = !item.hasChild;
      });
      resolve(data);
    }
  };

  defaultOptions.value = {
    lazy: true,
    label: "name",
    value: "id",
    checkStrictly: true,
    leaf: "hasChild",
    lazyLoad: loadNode
  };

  const init = async () => {
    const { data } = await getDict({ parentId: dict.marketResources });
    data.forEach((item: any) => {
      item.hasChild = !item.hasChild;
    });
    typeList.value = data;
  };

  const openDialog = async (option: any) => {
    await init();
    console.log(option);
    config.value = {
      title: "复制文件到市场资料",
      width: 20,
      height: "30vh",
      form: {
        formData: {
          typeId: "",
          databaseId: option.id,
          name: option.name,
          path: option.path,
          originalFileName: option.originalFileName,
          downNumber: 0,
          customPath: option.customPath,
          previewLink: option.previewLink,
          remark: option.remark,
          size: option.size
        },
        rules: {
          typeId: [{ required: true, message: "请选择类型" }]
        },
        attribute: {
          "label-suffix": ""
        }
      },
      api: insertMarketDatabase,
      column: [
        {
          type: "cascader",
          key: "typeId",
          formItemAttribute: {
            label: "类型"
          },
          attributes: {
            placeholder: "请选择",
            options: typeList,
            clearable: true,
            props: defaultOptions.value,
            changeFn: (val: any, originConfig: any, configModel: any, cascaderRef: any) => {
              let arrAddress = cascaderRef.getCheckedNodes();
              let names = arrAddress[0]["pathLabels"];
              console.log(names, val, originConfig);
            }
          },

          isHidden: true
        }
      ],
      transformData: (data: any) => {
        data.typeId = data.typeId[data.typeId.length - 1];
        return data;
      },
      message: "复制成功"
    };

    const options: DialogFormOptions = {
      config: config.value,
      successCallback: () => {}
    };

    dialogForm(options);
  };

  return {
    openDialog
  };
};
